/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servinf.ani.sincronizador.dao;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author mortiz
 */
public abstract class JPADAO <T, I extends Serializable> implements DAO<T, I> {

	@PersistenceContext(name = "sincronizadorPU")
	protected EntityManager em = null;
	
	protected Class<T> entityClass;

	public void setEntityClass(final Class<T> classToSet) {
		entityClass = classToSet;
	}
	
	/*
	 * Sets the entity manager.
	 */
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
            this.em = em;
	}

	@Transactional(readOnly = true)
	public T findById(final I id) {
            return getEm().find(entityClass, (Serializable) id);
	}

	@Transactional(readOnly = true)
	public List<T> findAll() {
                return  em.createQuery("SELECT e from " + entityClass.getName() + " e")
				.getResultList();
	}

	@Transactional(readOnly = false)
	public boolean update(T entity) {
		try {
                    getEm().merge(entity);
                    getEm().flush();
                    return true;
		} catch (Exception e) {
                    e.printStackTrace();
                    return false;
		}
	}

	@Transactional(readOnly = false)
	public boolean delete(I id) {
		try {
			T entity = this.findById(id);
			getEm().remove(entity);
			getEm().flush();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

        @Transactional(readOnly = false)
	public boolean create(final T entity) {
		try {
			getEm().persist(entity);
			getEm().flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public EntityManager getEm() {
		return em;
	}
}
